import Vue from 'vue'
let timer;
let reConnTimes = 0; //错误重连次数
let websock = {
	socket: ""
}

function websocketOnOpen() {
	//连接建立之后执行send方法发送数据
	console.log("连接建立成功");
	reConnTimes = 0;
	let loginUser = Vue.prototype.$loginUser.userInfo;
	console.log(loginUser);
	if (loginUser) {
		let actions = {
			userName: loginUser.chsName,
			type: 'onlineUsers'
		};
		websock.socket.send(JSON.stringify(actions));
	}
}

function websocketOnError(e) {
	console.log("连接异常", e);
	//连接建立失败重连
	reConnTimes++;
	if (reConnTimes < 3) {
		//重连只重试三次，仍失败则不再重试，交由心跳重试
		initWebSocket();
	}
}

function websocketOnMessage(e) {
	if (e.data === "pong") {
		console.log(e.data);
	} else if (e.data.indexOf("login") > -1) {
				console.log(123123123)
		const newArr = JSON.parse(e.data);
		const userInfo = Vue.prototype.$loginUser.userInfo;
		if (userInfo && userInfo.accountName === "root") {
			const oldArr = Vue.prototype.$onlines;
			const arrC = newArr.filter(a => !oldArr.some(b => b.id == a.id))
			const arrd = oldArr.filter(a => !newArr.some(b => b.id == a.id))
			arrC.forEach(item => {
				Vue.prototype.$Notice.success({
					title: '新消息',
					desc: item.userName + "在线",
					duration: 3
				});
			})
			arrd.forEach(item => {
				Vue.prototype.$Notice.success({
					title: '新消息',
					desc: item.userName + "下线",
					duration: 3
				});
			})
		}
		Vue.prototype.$onlines = newArr;
	} else if (e.data.indexOf("msg:") > -1) {
		Vue.prototype.$Notice.success({
			title: '新消息',
			desc: e.data.split("msg:")[1],
			duration: 0
		});
	} else if (e.data.indexOf("请勿重复执行") > -1) {
		//全局提醒
		if (e.data.indexOf(Vue.prototype.$loginUser.chsName) < 0) {
			Vue.prototype.$Notice.warning({
				title: '全局提醒',
				desc: e.data
			});
		}
	} else {
		console.log("接收数据", e.data);
	}
}

function websocketOnClose(e) {
	//关闭
	console.log("断开连接", e);
}

function initWebSocket() {
	//处理因开发，测试，生产环境不用，socket连接url不同
	let host = window.location.host;
	if (window.location.host.indexOf("localhost") > -1) {
		host = "localhost:9002";
	}
	//初始化weosocket
	const wsuri = `ws://${host}/bi-etl-api/imserver`;
	websock.socket = undefined;
	const newWebsock = new WebSocket(wsuri);
	newWebsock.onmessage = websocketOnMessage;
	newWebsock.onopen = websocketOnOpen;
	newWebsock.onerror = websocketOnError;
	newWebsock.onclose = websocketOnClose;
	websock.socket = newWebsock;
}

function websocketHeart() {
	timer = setInterval(function() {
		let actions = {
			type: "ping"
		};
		if (!websock.socket || websock.socket.readyState === 3) {
			console.log("webSocket连接已关闭，尝试重新连接！")
			initWebSocket();
		} else {
			websock.socket.send(JSON.stringify(actions));
		}
	}, 40000);
}
initWebSocket();
websocketHeart();
export default {
	websock,
	initWebSocket,
	websocketOnMessage
}
